import { CriteriaItem, LogicExpressionAssignment } from '@/components/complex/Rules';
import { EOperator } from '@/constants/config';

/**
 * 校验条件
 */
export const validateCriteria = (criteria: CriteriaItem) => {
  let errorMsg: string[] = [];
  if (!criteria?.conditions) {
    errorMsg.push('条件不可为空');
    return errorMsg;
  }
  
  const validateConditions = (conditions: CriteriaItem['conditions'], level: number) => {
    if (!conditions?.length) {
      return;
    }
    conditions.forEach((element, index) => {
      if (element) {
        const label = `${level}层第${index + 1}个条件`;
        if (!element.conditions?.length) {
          if (!element.left) {
            errorMsg.push(`${label}的左值不可为空`);
          }
          if (!element.operator) {
            errorMsg.push(`${label}的运算符不可为空`);
          }
          if (!element.rightType && element.operator !== EOperator.IsEmpty && element.operator !== EOperator.IsNotEmpty) {
            errorMsg.push(`${label}的值来源不可为空`);
          }
          if (!element.right && element.operator !== EOperator.IsEmpty && element.operator !== EOperator.IsNotEmpty) {
            errorMsg.push(`${label}的右值不可为空`);
          }
        } else {
          validateConditions(element.conditions, level + 1);
        }
      } else {
        errorMsg.push(`${level}层第${index + 1}个条件为空`);
      }
    });
  };
  
  validateConditions(criteria.conditions, 1);

  return errorMsg;
};


/**
 * 校验赋值表达式
 */
export const validateAssignments = (assignments: LogicExpressionAssignment[]) => {
  let errorMsg: string[] = [];
  if (!assignments?.length) {
    return errorMsg;
  }

  assignments.forEach((element, index) => {
    const label = `第${index + 1}个规则赋值`;
    if (element) {
      if (!element.left) {
        const desc = `${label}：第${index + 1}个赋值的变量不可为空`;
        errorMsg.push(desc);
      }
      if (!element.rightType) {
        const desc = `${label}：第${index + 1}个赋值的变量类型不可为空`;
        errorMsg.push(desc);
      }
      if (!element.rightFieldType) {
        const desc = `${label}：第${index + 1}个赋值的值类型不可为空`;
        errorMsg.push(desc);
      }
      if (!element.right) {
        const desc = `${label}：第${index + 1}个赋值的值不可为空`;
        errorMsg.push(desc);
      }
    }
  });

  return errorMsg;
};
